// ************************** Motor.c **********************************

#include "inc/hw_memmap.h"
#include "inc/hw_types.h"
#include "driverlib/debug.h"
#include "driverlib/gpio.h"
#include "driverlib/pwm.h"
#include "driverlib/sysctl.h"
//#include "motor.h"

#define PWM_SYSCTL_PORT_A           SYSCTL_PERIPH_GPIOF
#define PWM_SYSCTL_PORT_B           SYSCTL_PERIPH_GPIOG
#define PWM_PIN_A                   GPIO_PIN_0
#define PWM_PIN_B                   GPIO_PIN_1
#define PWM_PORT_A_BASE             GPIO_PORTF_BASE
#define PWM_PORT_B_BASE             GPIO_PORTG_BASE
#define PWM_MODULE                  PWM_GEN_0
#define PWM_PIN_OUT_A               PWM_OUT_0
#define PWM_PIN_OUT_B               PWM_OUT_1
#define PWM_OUT_PINS                PWM_OUT_0_BIT | PWM_OUT_1_BIT


// **********************************************************************
// ************************** GLOBALS *********************************
// ******************************************************************
unsigned long PWM_Period;
// ******************************************************************
// ***********************************************************************

// 
void Motor_DutyCycle( unsigned long dutyCycle_A, unsigned long dutyCycle_B ){
      // Set duty cycle
  PWMPulseWidthSet(PWM_BASE, PWM_PIN_OUT_A, PWM_Period*dutyCycle_A/1000); 
  PWMPulseWidthSet(PWM_BASE, PWM_PIN_OUT_B, PWM_Period*dutyCycle_B/1000); 
}

void Motor_Freq( unsigned long freq ){
    // Calculate PWM period relative to the system clock
  PWM_Period = SysCtlClockGet() / freq; // Speed in Hz
   // Set the PWM period
  PWMGenPeriodSet(PWM_BASE, PWM_MODULE, PWM_Period);
}

void Motor_Init( void ){

    // Set PWM clock = sys clock
  SysCtlPWMClockSet(SYSCTL_PWMDIV_1);

    // Enable PWM Generator
  SysCtlPeripheralEnable(SYSCTL_PERIPH_PWM);
    // Enable Port PWM pins
  SysCtlPeripheralEnable(PWM_SYSCTL_PORT_A);
  SysCtlPeripheralEnable(PWM_SYSCTL_PORT_B);

    // Set IO pins as PWM
  GPIOPinTypePWM(PWM_PORT_A_BASE, PWM_PIN_A);
  GPIOPinTypePWM(PWM_PORT_B_BASE, PWM_PIN_B);

  PWMGenConfigure(PWM_BASE, PWM_MODULE,
                  PWM_GEN_MODE_UP_DOWN | PWM_GEN_MODE_NO_SYNC);
  Motor_Freq( 500 );
  Motor_DutyCycle( 500, 750 );
    // Enable Output
  PWMOutputState(PWM_BASE, PWM_OUT_PINS, true);

    // Enable the PWM generator.
  PWMGenEnable(PWM_BASE, PWM_MODULE);
}

int Test_main( void ){
  unsigned long i;
  SysCtlClockSet(SYSCTL_SYSDIV_1 | SYSCTL_USE_OSC | SYSCTL_OSC_MAIN |
                   SYSCTL_XTAL_8MHZ);
  Motor_Init();
  while(1){
  }
  return 1;
}

